
<template>
  <el-form
    :model="localFormData"
    label-width="auto"
    style="max-width: 600px"
    ref="ruleFormRef"
    :rules="rules"
  >
    <el-form-item label="用户名" prop="username" required>
      <el-input v-model="localFormData.username" />
    </el-form-item>
    <el-form-item label="头像" prop="avatar" >
      <ThumbnailUpload
        :api="uploadFile"
        :maxSizeMB="2"
        :allowedExtensions="['.jpg', '.jpeg', '.png', '.gif']"
      />
    </el-form-item>
    <el-form-item label="是否启用" prop="isActive">
      <el-switch v-model="isActive" @change="handleStatusChange" />
    </el-form-item>
    <el-form-item label="角色" prop="role" required>
      <el-select v-model="localFormData.role" placeholder="请选择角色">
        <el-option
          v-for="item in userRoles"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="localFormData.phone" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="localFormData.email" />
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted,  defineExpose, watchEffect } from "vue";
import type { FormInstance } from "element-plus";
import * as Api from "@/api/index";
import { FormFactory } from "@/core/forms/form-factory";
import { UserFormData } from "@/core/forms/user-form";
import type { UserItem, CreateUserParams } from "@/api/types/user";
import ThumbnailUpload from "@/components/upload/ThumbnailUpload.vue";

const props = defineProps<{
  formData: UserItem;
  mode: "create" | "edit";
}>();

const ruleFormRef = ref<FormInstance>();
// 如果是编辑模式，初始化表单数据
const userRoles = [
  { label: "普通用户", value: "user" },
  { label: "管理员", value: "admin" },
  { label: "编辑", value: "editor" },
];
const localFormData = ref(FormFactory.create("user") as UserFormData);
const isActive=ref(true);
const rules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 30, message: "请输入4-15位用户名", trigger: "blur" },
  ],
  phone: [
    {
      required: false,
      message: "请输入手机号",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/, // 中国大陆手机号正则
      message: "请输入正确的11位手机号码",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: false,
      message: "请输入邮箱",
      trigger: "change",
    },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  role: [
    {
      required: true,
      message: "请选择角色",
    },
  ],
});
// 处理状态切换
const handleStatusChange = (val: boolean) => {
  localFormData.value.status = val ? "active" : "inactive";
};

// 暴露给父组件的异步提交方法
const submit = async () => {
  if (!ruleFormRef.value) return;

  return ruleFormRef.value
    .validate()
    .then(async (valid) => {
      if (!valid) return false;
      const submitFormData = localFormData.value.toSubmitData();
      try {
        console.log("提交表单数据:", submitFormData);
        const response =
          props.mode === "create"
            ? await Api.createUser(submitFormData)
            : await Api.updateUser(props.formData.id, submitFormData);
        return true;
      } catch (err) {
        throw err; // 会被外部的catch捕获
      }
    })
    .catch((err) => {
      console.error("错误:", err);
      return false;
    });
};
const uploadFile=async (file: File) => { 
  try {
    // 这里实现你的上传逻辑，通常使用axios或fetch
    // 返回上传后的文件URL
    const formData = new FormData();
    formData.append("file", file);

    const response = await Api.upload("/upload/file", formData, "", {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    console.log(response);
    return response.url; // 假设后端返回包含url字段
  } catch (error) {
    console.log(error);
  }
};
// 自动响应props变化的智能初始化
watchEffect(() => {
  if (props.mode === "edit" && props.formData) {
    console.log("编辑模式，初始化表单数据", props.formData);
    localFormData.value = FormFactory.createFromExisting(
      "user",
      props.formData
    ) as UserFormData;
  } else {
    localFormData.value = FormFactory.create("user") as UserFormData;
  }
});
defineExpose({ submit });
onMounted(() => {});
</script>
<style scoped lang="scss"></style>
